<?php
header('Content-Type: application/json; charset: UTF-8');

include_once(dirname(__FILE__).'/config.php');
$store = ARC2::getStore($arc_config);

function strSlice($str, $start, $end) {
    $end = $end - $start;
    return substr($str, $start, $end);
}

$q = <<<EOT
PREFIX vocabs: <http://desanti.org/schemas/vocabularies#>
PREFIX cols: <http://desanti.org/schemas/collections#>
SELECT ?subject ?classLabel ?objectLabel ?subjectTypeLabel ?subjectLabel ?subjectThumbnail1 ?subjectThumbnail2 ?firstPage WHERE {
  ?subject ?relation ?object .
  ?class a vocabs:Class .
  ?class rdfs:label ?classLabel .
  ?object a ?class .
  ?object rdfs:label ?objectLabel .
  ?subject a ?subjectType .
  ?subjectType rdfs:label ?subjectTypeLabel .
  OPTIONAL {
    ?subject  rdfs:label ?subjectLabel .
  } .
  OPTIONAL {
    ?subject cols:thumbnail ?subjectThumbnail1 .
  } .
  OPTIONAL {
    ?subject cols:pages ?pages .
    ?pages <http://www.w3.org/1999/02/22-rdf-syntax-ns#_1> ?firstPage .
    ?firstPage cols:thumbnail ?subjectThumbnail2 .
  } .
}
EOT;

$rs = $store->query($q);
if(!$store->getErrors()){
	$rows = $rs['result']['rows'];

	foreach($rows as $row){
		$items[$row['subject']][$row['classLabel']][] =
			rawurldecode($row['objectLabel']);
		$items[$row['subject']]['type'] = rawurldecode($row['subjectTypeLabel']);
		$items[$row['subject']]['id'] = $row['subject'];
		$items[$row['subject']]['label'] = $row['subject'];
		if($row['subjectLabel']){ 
			$items[$row['subject']]['label'] = rawurldecode($row['subjectLabel']);
		}
		if($row['subjectThumbnail1']){
			$items[$row['subject']]['thumbnail'] = $row['subjectThumbnail1'];
			$items[$row['subject']]['href'] = 'javascript:self.opener.DESANTI.openPage("' .
				$row['subject'] . '"); self.opener.focus( )';
		}
		if($row['subjectThumbnail2']){
			$items[$row['subject']]['thumbnail'] = $row['subjectThumbnail2'];
			$items[$row['subject']]['href'] = 'javascript:self.opener.DESANTI.openPage("' .
				$row['firstPage'] . '"); self.opener.focus( )';
		}
		
	}
}
$q = <<<EOT
PREFIX vocabs: <http://desanti.org/schemas/vocabularies#>
PREFIX trans: <http://desanti.org/schemas/transcriptions#>
PREFIX cols: <http://desanti.org/schemas/collections#>

SELECT * WHERE {
  ?p a cols:Page .
  ?p cols:thumbnail ?thumb .
  ?p trans:hasInterval ?i .
  ?i trans:hasTerm ?t .
  ?t a ?c .
  ?t rdfs:label ?tLabel .
  ?c rdfs:label ?cLabel .
}
EOT;

$rs = $store->query($q);
if(!$store->getErrors()){
	foreach($rs['result']['rows'] as $row){
		$items[$row['p']][$row['cLabel']][] = rawurldecode($row['tLabel']);
		$items[$row['p']]['type'] = 'Page';
		$items[$row['p']]['id'] = $row['p'];
		$items[$row['p']]['label'] = $row['p'];
		$items[$row['p']]['thumbnail'] = $row['thumb'];
		$items[$row['p']]['href'] = 'javascript:self.opener.DESANTI.openPage("' .
		  $row['p'] . '"); self.opener.focus( )';
	}
}

$items = array('items'=>array_values($items));
print_r(json_encode($items));
?>
